<template>
  <!--隐藏两个表头-->
  <div class="contain">
    <div class="contain-button">
      <Item class="button-left" @active="addItem" :is-active="curMenu === 'add'">
        <img src="../assets/add.png" alt="" class="icon">添加
      </Item>
      <Item class="button-left" @active="editItem" :is-active="curMenu === 'edit'">
        <img src="../assets/edit1.png" alt="" class="icon">编辑
      </Item>
      <Item class="button-left" @active="deleteItem" :is-active="curMenu === 'delete'">
        <img src="../assets/delete.png" alt="" class="icon">删除
      </Item>
      <Item class="button-left" @active="okItem">
        <img src="../assets/ok.png" alt="" class="icon">确认
      </Item>
      <div class="button-right">
        <SearchText :type="head" class="search" @search="handlerSearch"></SearchText>
      </div>
    </div>
    <table border="1" cellspacing="0" cellpadding="10" class="table" style="table-layout: fixed">

      <thead class="head">
      <tr>
        <th class="checkbox">
          <Item>
            <input type="checkbox" @click="selectAll" ref="topCheckbox" disabled :checked="checked">
          </Item>
        </th>
        <th class="checkbox">
          <Item>
            序列
          </Item>
        </th>
        <th style="word-wrap:break-word;" v-for="item in head.slice(2)">
          <Item>{{ item }}</Item>
        </th>
      </tr>
      </thead>

      <!--数据体-->
      <tbody class="data">
      <tr v-for="(item,i) in data.slice((this.curPage-1)*this.pageTotal,this.curPage*this.pageTotal)" :ref="'row'"
          :key="item.id">
        <td>
          <Item>
            <input type="checkbox" @change="changeSelect(i)" disabled :checked="checked">
          </Item>
        </td>

        <td>
          <Item>
            {{ i + 1 }}
          </Item>
        </td>

        <td style="word-wrap:break-word;" v-for="(e,j) in item.data.slice(2)" :contentEditable="contentEditable"
            @blur="recordUpdate(i,j,e)">
          {{ e }}
        </td>
      </tr>

      <!--增加列使用-->
      <tr ref="addRow" hidden>
        <td>
          <Item>
            <input type="checkbox" :name="'checkbox,that is dont allow name'" disabled :checked="checked">
          </Item>
        </td>
        <td>
          <Item>
            {{ this.data.length + 1 }}
          </Item>
        </td>
        <td style="word-wrap:break-word;" v-for="(e,i) in head.slice(2)" :contentEditable="true" ref="addData">
        </td>
      </tr>
      </tbody>
    </table>
    <div class="contain-button" style="text-align: center">
      <PageSelect :total="this.data.length" :page-total="this.pageTotal" @selectPage="changePage"></PageSelect>
    </div>
  </div>
</template>

<script>
import Item from "@/components/Item";
import TableButton from "@/components/TableButton";
import SearchText from "@/components/SearchText";
import PageSelect from "@/components/PageSelect";

export default {
  name: "Table",
  components: {
    Item,
    TableButton,
    SearchText,
    PageSelect,
  },
  created() {
    //深拷贝
    this.srcData = [];
    for (let i = 0; i < this.data.length; i++) {
      var item = {};
      item['id'] = this.data[i]['id'];
      var arr = [];
      for (let j = 0; j < this.data[i]['data'].length; j++) {
        arr[j] = this.data[i]['data'][j];
      }
      item['data'] = arr;
      this.srcData.push(item);
    }
  },
  data() {
    return {
      checked: false,
      contentEditable: false,
      cacheSelect: [],//存选中元素下标
      curMenu: "", //当前菜单
      srcData: [],//源数据
      //返回改变的数据
      //[type,[row,args...]...]格式
      changeData: [],
      curPage: 1,
      pageTotal: 10,
      // total: this.data.length,
    }
  },
  props: {
    head: {
      type: Array,
    },
    data: {
      type: Array,
    },
  },
  methods: {
    recordUpdate(i, j, oldValue) {
      var newValue = this.$refs.row['' + i].getElementsByTagName('td')[j + 2].innerHTML;
      if (oldValue === newValue) {
        for (let k = 1; k < this.changeData.length; k++) {
          if (this.changeData[k]['row'] === i && this.changeData[k]['col'] === j) {
            this.changeData.splice(k, 1);
            break;
          }
        }
        return;
      }
      var update = {row: i, col: j, value: newValue};
      for (let k = 1; k < this.changeData.length; k++) {
        if (this.changeData[k]['row'] === update['row'] && this.changeData[k]['col'] === update['col']) {
          this.changeData.splice(k, 1);
          break;
        }
      }
      this.changeData.push(update);
    },
    selectAll() {
      this.checked = this.$refs.topCheckbox.checked;
      this.cacheSelect.splice(0, this.cacheSelect.length);
      if (!this.checked) return;

      for (let i = 0; i < this.$refs.row.length; i++) {
        this.cacheSelect.push(i);
      }
    },

    addItem() {
      this.doSelectMenu('add');
      this.$refs.addRow.removeAttribute('hidden');
    },

    deleteItem() {
      this.doSelectMenu('delete');
      this.$refs.topCheckbox.removeAttribute('disabled');

      var rowList = this.$refs.row;
      for (let i = 0; i < rowList.length; i++) {
        rowList[i].getElementsByTagName('input')[0].removeAttribute('disabled');
      }
    },

    editItem() {
      this.doSelectMenu('edit');
      this.changeData[0] = 'update';
      this.contentEditable = true;
    },

    okItem() {
      if (this.curMenu === 'ok') return;
      //分情况处理
      if (this.curMenu === 'add') {
        this.handlerAdd();
      }

      if (this.curMenu === 'delete') {
        this.handlerDelete();
      }

      if (this.curMenu === 'edit') {
        this.handlerUpdate();
      }
      //发送给后端
      if (this.changeData.length > 1) {
        this.$emit('tableChange', this.changeData);
      }
      //还原状态
      this.curMenu = 'ok';
      this.back();
    },

    doSelectMenu(menu) {
      if (this.curMenu === menu) return;

      //更换菜单
      this.curMenu = menu;
      this.back();
    },

    changeSelect(select) {
      var cur = this.$refs.row[select].getElementsByTagName('input')[0];
      if (cur.checked) {
        if (this.cacheSelect.includes(select)) return;
        this.cacheSelect.push(select);
      } else {
        if (!this.cacheSelect.includes(select)) return;
        let index = this.cacheSelect.indexOf(select);
        this.cacheSelect.splice(index, 1);
      }
    },

    back() {
      //清空本地变更数据
      this.changeData.splice(0, this.changeData.length);
      //清空选中数组
      this.cacheSelect.splice(0, this.cacheSelect.length);
      //状态处理
      this.$refs.topCheckbox.checked = false;
      this.$refs.topCheckbox.setAttribute('disabled', 'disabled');
      //不可编辑状态
      this.contentEditable = false;
      //不选中状态
      this.checked = false;
      //移除disabled属性
      var rowList = this.$refs.row;
      for (let i = 0; i < rowList.length; i++) {
        rowList[i].getElementsByTagName('input')[0].setAttribute('disabled', 'disabled');
      }
      //还原添加栏
      this.$refs.addRow.setAttribute('hidden', '');
    },

    handlerAdd() {
      const dataList = this.$refs.addData;
      const arr = [Date.now().toString(), Date.now().toString()];
      for (let i = 0; i < dataList.length; i++) {
        arr.push(dataList[i].innerHTML);
        //还原空行
        dataList[i].innerHTML = '';
      }
      //传送改变数据给后端
      this.changeData[0] = 'add';
      this.changeData[1] = arr;
      //数据重新渲染
      this.data.push({id: arr[0], data: arr});
      //隐藏编辑行
      this.$refs.addRow.setAttribute('hidden', '');
    },

    handlerDelete() {
      console.log(this.data)
      this.changeData[0] = 'delete';
      for (let i = 0; i < this.cacheSelect.length; i++) {
        const index = this.cacheSelect[i];
        const list = this.$refs['row']['' + index].getElementsByTagName('td');
        const arr = [];
        const id = parseInt(list[1].getElementsByTagName('div')[0].innerHTML) - 1;
        arr.push(this.data[id]['data'][0])
        arr.push(this.data[id]['data'][1])
        for (let j = 2; j < list.length; j++) {
          arr.push(list[j].innerHTML);
        }
        this.changeData.push(arr);
      }

      this.cacheSelect.sort((a, b) => (b - a))
      for (let i = 0; i < this.cacheSelect.length; i++) {
        this.data.splice(this.cacheSelect[i], 1);
      }
    },

    handlerSearch(type, text) {
      if (text === '') {
        //深拷贝
        this.data = [];
        for (let i = 0; i < this.srcData.length; i++) {
          var item = {};
          item['id'] = this.srcData[i]['id'];
          var arr = [];
          for (let j = 0; j < this.srcData[i]['data'].length; j++) {
            arr[j] = this.srcData[i]['data'][j];
          }
          item['data'] = arr;
          this.data.push(item);
        }
        return;
      }
      var record = [];
      for (let i = 0; i < this.data.length; i++) {
        console.log(this.data[i]);
        if (!('' + this.data[i]['data'][type]).includes(text, 0)) {
          record.push(i);
        }
      }

      //重熏染
      for (let i = record.length - 1; i >= 0; i--) {
        this.data.splice(record[i], 1);
      }
    },
    handlerUpdate() {

    },
    changePage(page) {
      console.log(page);
      this.curPage = page;
    }
  }
}
</script>

<style scoped>

.contain {
  width: 100%;
  height: 100%;
}

.table {
  width: 98%;
}

.head,
.data {
  font-family: SimSun;
  font-size: 15px;
}

.head {
  background-color: #f4f4f4;
  font-weight: bold;
}

.data {
  background-color: #ffffff;
}

.checkbox {
  width: 30px;
}

.contain-button {
  width: 98%;
  background-color: #f1f1f1;
  border: 1px solid;
  height: 50px;
  line-height: 50px;
}

.button-left {
  float: left;
  font-size: 15px;
  font-family: SimSun;
  margin-left: 15px;
  width: 5%;
}

.button-right {
  float: right;
  margin-right: 30px;
}

.icon {
  width: 12px;
  height: 12px;
}
</style>